package libcore.datastore

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.withContext
import libcore.util.appContext

//val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings2")

abstract class AbsStore(/*val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())*/) {
    abstract val fileName: String

    val dataStore by lazy { createDatastore(fileName) }

    // 判断T的类型，如果不是基本类型，转成json
    suspend fun <T> saveData(key: String, data: T?) {
        withContext(Dispatchers.IO) {
            dataStore.edit {
                if (data == null) {
                    it.remove(stringPreferencesKey("name"))
                } else {
                    it[stringPreferencesKey("name")] = key
                }

            }
        }
    }

//    suspend fun <T> getData(key: String): T? {
//        withContext(Dispatchers.IO) {
//            dataStore.data.first()[stringPreferencesKey(key)]
//        }
//    }

}

fun createDatastore(name: String): DataStore<Preferences> {
    check(name.isNotEmpty()) { "kotprefName为空，请显示指定sp名称！" }

    return PreferenceDataStoreFactory.create(
        migrations = listOf(SharedPreferencesMigration(appContext, name)),
    ) {
        appContext.preferencesDataStoreFile(name)
    }
}